<template>
  <div class="modal fade" ref="modalRef">
    <div class="modal-dialog" :class="sizeClass">
      <div class="modal-content" v-if="rendered">
        <div class="modal-header">
          <h5 class="modal-title">{{ title }}</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <slot></slot>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue'
import { Modal } from 'bootstrap';

const emit = defineEmits(['update:modelValue']);

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  title: {
    type: String,
    required: true
  },
  size: {
    type: String
  },
  backdrop: {
    default: 'static'
  },
  destory: {
    type: Boolean,
    default: true
  }
})

const sizeClass = computed(() => {
  return props.size ? 'modal-' + props.size : null;
})

const modalRef = ref(null);

const rendered = ref(false);

let modalObj = null;

onMounted(() => {
  modalObj = new Modal(modalRef.value, {
    backdrop:props.backdrop
  });

  modalRef.value.addEventListener('hide.bs.modal', () => {

    emit("update:modelValue", false)
    if (props.destory) {
      rendered.value = false;
    }
  })

  if (props.modelValue) {
    rendered.value = true
    modalObj.show();
  }
})

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      rendered.value = true;
      modalObj.show();
    } else {
      if (props.destory) {
        rendered.value = false;
      }
      modalObj.hide();
    }
  }
)
</script>